package com.cavy.platform.server.domain;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.CavyConfig;
import com.cavy.platform.server.util.FileUtils;
import com.cavy.platform.server.util.HttpServletResponseHelper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@EqualsAndHashCode(callSuper = true)
@Data
public class FileConfigMap extends AbstractConfigMap {
    private String fileName;

    public FileConfigMap() {
        type = ConfigMapType.FILE;
    }

    @Override
    public void getValue(HttpServletResponse response) {
        File target = getFile();
        if (!target.exists()) {
            return;
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("fileName", fileName);
        HttpServletResponseHelper.writeFile(target, response);
    }

    @JsonIgnore
    public File getFile() {
        CavyConfig bean = BeansProvider.getBean(CavyConfig.class);
        assert bean != null;
        File parent = bean.getConfigMap().getFileDir();
        return new File(parent, getWorkspaceFileName());
    }

    private String getWorkspaceFileName() {
        return String.format("%s-%s", getWorkSpace(), getFileName());
    }

    @Override
    public void delete() {
        super.delete();
        File file = getFile();
        if (file.exists()) {
            FileUtils.delete(file);
        }
    }
}
